package com.dynomedia.esearch.util.groupkeycache;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dynomedia.esearch.util.groupkeycache.util.ConsumerThreadPool;

/**
 * GroupkeyCache 内置的状态信息监控线程
 * @author Administrator
 *
 */
public class Monitor implements Runnable{
	
	private static final Log logger = LogFactory.getLog(Monitor.class);
	
	private static long starttime = System.currentTimeMillis();
	
	private static Map<Long,Groupkey> localGroupkeys = new HashMap<Long,Groupkey>();
	
	static{
		ConsumerThreadPool.submit(new Monitor());
	}
	
	public static void start(){}

	public void run(){
		StringBuffer sb = new StringBuffer();
		
		while(ConsumerThreadPool.isRunning()){
			
			try{
				
				int bufferedkeysize = KeyBuffer.size();
				
				localGroupkeys = GroupkeyCache.getGroupkeys(localGroupkeys);	
				
				Collection<Groupkey> gks = localGroupkeys.values();
				int needFlushGkcount = 0;
				int totalSampledTopkeysCount = 0;
				int totalSortedTopkeysCount = 0;
				for(Groupkey gk:gks){
					if(gk.needSort()) needFlushGkcount++;
					totalSampledTopkeysCount = totalSampledTopkeysCount + gk.getSampledTopkeys().size();
					totalSortedTopkeysCount = totalSortedTopkeysCount + gk.getSortedTopkeys().size();
				}
				
				sb.append("\r\t[GroupkeyCache Status]:"+((bufferedkeysize == 0 && needFlushGkcount==0)?"idled":"busy"));
				sb.append("\r\t[KeyBuffer.size]:"+bufferedkeysize);
													
				sb.append("\r\t[GroupkeyCache.Groupkeys.size]:"+gks.size());
				sb.append("\r\t[GroupkeyCache.Groupkeys.totalSortedTopkeysCount]:"+totalSortedTopkeysCount);
				sb.append("\r\t[GroupkeyCache.Groupkeys.totalSampledTopkeysCount]:"+totalSampledTopkeysCount);
								
				sb.append("\r\t[GroupkeyCache.Groupkeys.needFlushGkcount]:"+needFlushGkcount);
				sb.append("\r\t[maxMemory]:"+(((Runtime.getRuntime().maxMemory())/1024/1024)));
				sb.append("\t[totalMemory]:"+(((Runtime.getRuntime().totalMemory())/1024/1024)));
				sb.append("\t[freeMemory]:"+(((Runtime.getRuntime().freeMemory())/1024/1024)));
				sb.append("\r\t[GroupkeyCache.totalRuningTime]:"+((System.currentTimeMillis()-starttime)/1000f+" s"));						
				
				localGroupkeys.clear();
				logger.info(sb.toString());
				sb.delete(0,sb.length());
				
				Thread.sleep(1000);
			}catch(Exception e){
				logger.error("Monitor run error!",e);
			}
		}
		
	}
}
